﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Issues.TheConquestOfSettlementIssueBehavior
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.MapEvents;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Issues
{
  public class TheConquestOfSettlementIssueBehavior : CampaignBehaviorBase
  {
    private const IssueBase.IssueFrequency TheConquestOfSettlementIssueFrequency = IssueBase.IssueFrequency.VeryCommon;

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.OnCheckForIssue));
    }

    private void OnCheckForIssue(Hero hero)
    {
      Settlement targetSettlement;
      if (this.ConditionsHold(hero, out targetSettlement))
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnStartIssue), typeof (TheConquestOfSettlementIssueBehavior.TheConquestOfSettlementIssue), IssueBase.IssueFrequency.VeryCommon, (object) targetSettlement));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (TheConquestOfSettlementIssueBehavior.TheConquestOfSettlementIssue), IssueBase.IssueFrequency.VeryCommon));
    }

    private bool ConditionsHold(Hero issueGiver, out Settlement targetSettlement)
    {
      targetSettlement = (Settlement) null;
      if (issueGiver.IsLord && issueGiver.MapFaction.IsKingdomFaction && issueGiver.IsFactionLeader && !issueGiver.IsPrisoner && issueGiver.GetMapPoint() != null && issueGiver.Clan.Settlements.Any<Settlement>((Func<Settlement, bool>) (x => x.IsFortification)))
      {
        MBList<Settlement> e = new MBList<Settlement>();
        foreach (Town allTown in (List<Town>) Campaign.Current.AllTowns)
        {
          if (allTown.MapFaction.IsAtWarWith(issueGiver.MapFaction) && (double) allTown.Settlement.Position2D.DistanceSquared(issueGiver.GetMapPoint().Position2D) < 7500.0)
            e.Add(allTown.Settlement);
        }
        foreach (Town allCastle in (List<Town>) Campaign.Current.AllCastles)
        {
          if (allCastle.MapFaction.IsAtWarWith(issueGiver.MapFaction) && (double) allCastle.Settlement.Position2D.DistanceSquared(issueGiver.GetMapPoint().Position2D) < 7500.0)
            e.Add(allCastle.Settlement);
        }
        if (e.Count > 0)
          targetSettlement = e.GetRandomElement<Settlement>();
      }
      return targetSettlement != null;
    }

    private IssueBase OnStartIssue(in PotentialIssueData pid, Hero issueOwner)
    {
      return (IssueBase) new TheConquestOfSettlementIssueBehavior.TheConquestOfSettlementIssue(issueOwner, (Settlement) pid.RelatedObject);
    }

    public override void SyncData(IDataStore dataStore)
    {
    }

    public class TheConquestOfSettlementIssue : IssueBase
    {
      private const int QuestTimeLimit = 60;
      [SaveableField(10)]
      private Settlement _targetSettlement;

      internal static void AutoGeneratedStaticCollectObjectsTheConquestOfSettlementIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._targetSettlement);
      }

      internal static object AutoGeneratedGetMemberValue_targetSettlement(object o)
      {
        return (object) ((TheConquestOfSettlementIssueBehavior.TheConquestOfSettlementIssue) o)._targetSettlement;
      }

      public override TextObject Title
      {
        get
        {
          TextObject title = new TextObject("{=mvzh0HVk}The Conquest of {TARGET_SETTLEMENT}");
          title.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          return title;
        }
      }

      public override TextObject Description
      {
        get
        {
          TextObject parent = new TextObject("{=xeZR3r5u}{QUEST_GIVER.LINK} wants you siege and take over the {TARGET_SETTLEMENT}");
          parent.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          TextObject briefByIssueGiver = new TextObject("{=Oi20UrO2}Our war with the {TARGET_SETTLEMENT_FACTION_INFORMAL_NAME} is going well enough. But there are some who say that we don't have enough to show for all the blood and silver we've spent. A clear victory at this stage would do a lot of good. I think I would like to see our banner flying from the towers of {TARGET_SETTLEMENT}.[ib:normal2][if:convo_thinking]");
          briefByIssueGiver.SetTextVariable("TARGET_SETTLEMENT_FACTION_INFORMAL_NAME", this._targetSettlement.MapFaction.InformalName);
          briefByIssueGiver.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          return briefByIssueGiver;
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get
        {
          TextObject parent = new TextObject("{=qKrUyqsD}Of course, my {?QUEST_GIVER.GENDER}lady{?}lord{\\?}. But sieges are always costly...");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=yf3NVFi0}Yes, they are. That's why I am offering you the sum of {REWARD_GOLD}{GOLD_ICON} if you can take {TARGET_SETTLEMENT} within {TIME_LIMIT} days.[if:convo_thinking] I count you among the most resourceful of my captains. I think you can do this, with courage, Heaven's favor and a bit of luck. Can I tell my other lords that you will do this?");
          explanationByIssueGiver.SetTextVariable("REWARD_GOLD", this.RewardGold);
          explanationByIssueGiver.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          explanationByIssueGiver.SetTextVariable("TIME_LIMIT", 60);
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get
        {
          TextObject solutionAcceptByPlayer = new TextObject("{=scmTEn90}You may tell them. {TARGET_SETTLEMENT} will be ours within 60 days.");
          solutionAcceptByPlayer.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          return solutionAcceptByPlayer;
        }
      }

      public override bool IsThereAlternativeSolution => false;

      public override bool IsThereLordSolution => false;

      protected override int RewardGold => 20000;

      public TheConquestOfSettlementIssue(Hero issueOwner, Settlement targetSettlement)
        : base(issueOwner, CampaignTime.DaysFromNow(60f))
      {
        this._targetSettlement = targetSettlement;
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        return issueEffect == DefaultIssueEffects.SettlementSecurity || issueEffect == DefaultIssueEffects.SettlementLoyalty ? -1f : 0.0f;
      }

      protected override void OnGameLoad()
      {
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new TheConquestOfSettlementIssueBehavior.TheConquestOfSettlementIssueQuest(questId, this.IssueOwner, this._targetSettlement, CampaignTime.DaysFromNow(60f), this.RewardGold);
      }

      public override IssueBase.IssueFrequency GetFrequency()
      {
        return IssueBase.IssueFrequency.VeryCommon;
      }

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flags,
        out Hero relationHero,
        out SkillObject skill)
      {
        relationHero = (Hero) null;
        skill = (SkillObject) null;
        flags = IssueBase.PreconditionFlags.None;
        if ((double) issueGiver.GetRelationWithPlayer() < -10.0)
        {
          flags |= IssueBase.PreconditionFlags.Relation;
          relationHero = issueGiver;
        }
        if (issueGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          flags |= IssueBase.PreconditionFlags.AtWar;
        if (Clan.PlayerClan.Kingdom != issueGiver.MapFaction)
          flags |= IssueBase.PreconditionFlags.NotInSameFaction;
        if (Clan.PlayerClan.IsUnderMercenaryService)
          flags |= IssueBase.PreconditionFlags.ClanIsMercenary;
        return flags == IssueBase.PreconditionFlags.None;
      }

      public override bool IssueStayAliveConditions()
      {
        return this._targetSettlement.MapFaction.IsAtWarWith(this.IssueOwner.MapFaction) && this.IssueOwner.MapFaction.IsKingdomFaction && this.IssueOwner.Clan.Settlements.Any<Settlement>((Func<Settlement, bool>) (x => x.IsFortification));
      }

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }
    }

    public class TheConquestOfSettlementIssueQuest : QuestBase
    {
      private const int SuccessLoyaltySecurityBoost = 10;
      private const int LesserSuccessLoyaltySecurityBoost = 2;
      private const int SuccessRelationBoost = 5;
      private const int LesserSuccessRelationBoost = 1;
      private const int TimeoutSecurityLoyaltyPenalty = -10;
      private const int TimeoutRelationyPenalty = -10;
      [SaveableField(10)]
      private Settlement _targetSettlement;

      internal static void AutoGeneratedStaticCollectObjectsTheConquestOfSettlementIssueQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._targetSettlement);
      }

      internal static object AutoGeneratedGetMemberValue_targetSettlement(object o)
      {
        return (object) ((TheConquestOfSettlementIssueBehavior.TheConquestOfSettlementIssueQuest) o)._targetSettlement;
      }

      public override TextObject Title
      {
        get
        {
          TextObject title = new TextObject("{=mvzh0HVk}The Conquest of {TARGET_SETTLEMENT}");
          title.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          return title;
        }
      }

      public override bool IsRemainingTimeHidden => false;

      private TextObject QuestStartedLog
      {
        get
        {
          TextObject parent = new TextObject("{=b1T6qywr}{QUEST_GIVER.LINK} from {QUEST_GIVER.FACTION} asked you to take over {TARGET_SETTLEMENT} in the name of {QUEST_GIVER.FACTION} to fortify war efforts. {QUEST_GIVER.LINK} said {?QUEST_GIVER.GENDER}she{?}he{\\?} will aid you with {REWARD}{GOLD_ICON} once the {TARGET_SETTLEMENT} is fallen.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent, true);
          parent.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          parent.SetTextVariable("REWARD", this.RewardGold);
          return parent;
        }
      }

      private TextObject WarDeclaredQuestCancelLog
      {
        get
        {
          TextObject parent = new TextObject("{=PakhagOy}Your clan is now at war with {QUEST_GIVER.LINK}'s lord. Your agreement with {QUEST_GIVER.LINK} was canceled.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerDeclaredWarQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=bqeWVVEE}Your actions have started a war with {QUEST_GIVER.LINK}'s faction. {?QUEST_GIVER.GENDER}She{?}He{\\?} cancels your agreement and the quest is a failure.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject QuestTimeOutFailLog
      {
        get
        {
          TextObject parent = new TextObject("{=lEcg67Qk}You have failed to take over {TARGET_SETTLEMENT} in time. {QUEST_GIVER.LINK} is disappointed that you have failed to take the fortress in time.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          return parent;
        }
      }

      private TextObject QuestSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=6d2VIgH3}{QUEST_GIVER.LINK}: Thank you. My lords see you as an example, and see your conquest of {TARGET_SETTLEMENT} as be a stepping stone toward further victories. {?QUEST_GIVER.GENDER}She{?}He{\\?} is grateful for your service and gave you {REWARD}{GOLD_ICON}.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          parent.SetTextVariable("REWARD", this.RewardGold);
          return parent;
        }
      }

      private TextObject QuestLesserSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=1NtZ4BJh}{QUEST_GIVER.LINK}: Thank you. My lords see the conquest of {TARGET_SETTLEMENT} was a stepping stone toward further victories. {?QUEST_GIVER.GENDER}She{?}He{\\?} is grateful for your service. Because you didn't lead the army {?QUEST_GIVER.GENDER}She{?}He{\\?} gave you {LESSER_REWARD}{GOLD_ICON} of denars.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          return parent;
        }
      }

      private TextObject TargetSettlementTakenByAnotherFaction
      {
        get
        {
          TextObject parent = new TextObject("{=diUtbbaH}{TARGET_SETTLEMENT} is taken by {NEW_OWNER_FACTION}. Your agreement with {QUEST_GIVER.LINK} is no longer valid.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          return parent;
        }
      }

      private TextObject TargetSettlementTakenByPlayerFaction
      {
        get
        {
          TextObject parent = new TextObject("{=bEak0k5N}{TARGET_SETTLEMENT} is taken. You did not participate in this battle. Your agreement with {QUEST_GIVER.LINK} is moot.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          return parent;
        }
      }

      private TextObject LeftFaction
      {
        get
        {
          TextObject parent = new TextObject("{=d8TeoRNf}You are no longer in the same faction with {QUEST_GIVER.LINK}. Your agreement with {QUEST_GIVER.LINK} is no longer valid.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject DefectedToAnotherFaction
      {
        get
        {
          TextObject parent = new TextObject("{=8iVkBa6D}{TARGET_SETTLEMENT_OWNER.LINK} has defected to {FACTION_NAME} along with {TARGET_SETTLEMENT}. Your agreement with {QUEST_GIVER.LINK} is moot.");
          StringHelpers.SetCharacterProperties("TARGET_SETTLEMENT_OWNER", this._targetSettlement.OwnerClan.Leader.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
          return parent;
        }
      }

      private TextObject NoLongerEnemy
      {
        get
        {
          TextObject parent = new TextObject("{=HknxaCpK}{TARGET_SETTLEMENT_OWNER.FACTION} and {QUEST_GIVER.FACTION} had made peace. Your agreement with {QUEST_GIVER.LINK} is moot.");
          StringHelpers.SetCharacterProperties("TARGET_SETTLEMENT_OWNER", this._targetSettlement.OwnerClan.Leader.CharacterObject, parent, true);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent, true);
          return parent;
        }
      }

      public TheConquestOfSettlementIssueQuest(
        string questId,
        Hero questGiver,
        Settlement targetSettlement,
        CampaignTime duration,
        int rewardGold)
        : base(questId, questGiver, duration, rewardGold)
      {
        this._targetSettlement = targetSettlement;
        this.SetDialogs();
        this.InitializeQuestOnCreation();
      }

      protected override void SetDialogs()
      {
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine(new TextObject("{=QP3BbOW3}Very good. You have my blessing to summon an army if you wish, or, if you prefer to strike quickly, you may do so on your own...[ib:hip][if:convo_mocking_aristocratic]")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestAcceptedConsequences)).CloseDialog();
        TextObject npcText = new TextObject("{=ICNtSonV}How are your preparations to take {TARGET_SETTLEMENT} coming along, {PLAYER.NAME}? I have assured my other lords that you will take it, so it will look bad if you fail.");
        npcText.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.Name);
        TextObject textObject1 = new TextObject("{=m4pZhnyd}They are going as planned, my {?QUEST_GIVER.GENDER}lady{?}lord{\\?}...");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject1);
        TextObject textObject2 = new TextObject("{=jFXkosnJ}This may be tricky, my {?QUEST_GIVER.GENDER}lady{?}lord{\\?}...");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject2);
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").NpcLine(npcText).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).BeginPlayerOptions().PlayerOption(textObject1).NpcLine(new TextObject("{=opMDusHz}Good. I look forward to presenting you with your reward.")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(MapEventHelper.OnConversationEnd))).CloseDialog().PlayerOption(textObject2).NpcLine(new TextObject("{=R85IMErK}Well, if you fail we will deal with that, but I would prefer not to.")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(MapEventHelper.OnConversationEnd))).CloseDialog().EndPlayerOptions();
      }

      private void QuestAcceptedConsequences()
      {
        this.StartQuest();
        this.AddLog(this.QuestStartedLog);
        this.AddTrackedObject((ITrackableCampaignObject) this._targetSettlement);
      }

      protected override void HourlyTick()
      {
      }

      protected override void RegisterEvents()
      {
        CampaignEvents.WarDeclared.AddNonSerializedListener((object) this, new Action<IFaction, IFaction, DeclareWarAction.DeclareWarDetail>(this.OnWarDeclared));
        CampaignEvents.OnClanChangedKingdomEvent.AddNonSerializedListener((object) this, new Action<Clan, Kingdom, Kingdom, ChangeKingdomAction.ChangeKingdomActionDetail, bool>(this.OnClanChangedKingdom));
        CampaignEvents.MapEventStarted.AddNonSerializedListener((object) this, new Action<MapEvent, PartyBase, PartyBase>(this.OnMapEventStarted));
        CampaignEvents.SiegeCompletedEvent.AddNonSerializedListener((object) this, new Action<Settlement, MobileParty, bool, MapEvent.BattleTypes>(this.OnSiegeCompleted));
        CampaignEvents.OnSettlementOwnerChangedEvent.AddNonSerializedListener((object) this, new Action<Settlement, bool, Hero, Hero, Hero, ChangeOwnerOfSettlementAction.ChangeOwnerOfSettlementDetail>(this.OnSettlementOwnerChanged));
        CampaignEvents.MakePeace.AddNonSerializedListener((object) this, new Action<IFaction, IFaction, MakePeaceAction.MakePeaceDetail>(this.OnPeaceDeclared));
      }

      private void OnPeaceDeclared(
        IFaction faction1,
        IFaction faction2,
        MakePeaceAction.MakePeaceDetail detail)
      {
        if (this.QuestGiver.MapFaction.IsAtWarWith(this._targetSettlement.MapFaction))
          return;
        this.CompleteQuestWithCancel(this.NoLongerEnemy);
      }

      private void OnSettlementOwnerChanged(
        Settlement settlement,
        bool openToClaim,
        Hero newOwner,
        Hero oldOwner,
        Hero capturerHero,
        ChangeOwnerOfSettlementAction.ChangeOwnerOfSettlementDetail detail)
      {
        if (!this.IsOngoing || settlement != this._targetSettlement)
          return;
        if (newOwner == Hero.MainHero && detail == ChangeOwnerOfSettlementAction.ChangeOwnerOfSettlementDetail.ByBarter)
        {
          this.QuestSuccess(2);
        }
        else
        {
          if (newOwner.MapFaction == this.QuestGiver.MapFaction || newOwner.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
            return;
          TextObject byAnotherFaction = this.TargetSettlementTakenByAnotherFaction;
          byAnotherFaction.SetTextVariable("NEW_OWNER_FACTION", newOwner.MapFaction.EncyclopediaLinkWithName);
          this.CompleteQuestWithCancel(byAnotherFaction);
        }
      }

      private void OnSiegeCompleted(
        Settlement siegeSettlement,
        MobileParty attackerParty,
        bool isWin,
        MapEvent.BattleTypes battleType)
      {
        if (!isWin || siegeSettlement != this._targetSettlement)
          return;
        if (attackerParty.MapFaction == this.QuestGiver.MapFaction)
        {
          if (attackerParty == MobileParty.MainParty)
            this.QuestSuccess(10);
          else if (siegeSettlement.Party.MapEvent.InvolvedParties.Contains<PartyBase>(PartyBase.MainParty))
            this.QuestLesserSuccess();
          else
            this.CompleteQuestWithCancel(this.TargetSettlementTakenByPlayerFaction);
        }
        else
        {
          TextObject byAnotherFaction = this.TargetSettlementTakenByAnotherFaction;
          byAnotherFaction.SetTextVariable("NEW_OWNER_FACTION", attackerParty.MapFaction.EncyclopediaLinkWithName);
          this.CompleteQuestWithCancel(byAnotherFaction);
        }
      }

      private void QuestLesserSuccess()
      {
        TextObject lesserSuccessLog = this.QuestLesserSuccessLog;
        int num = this.RewardGold / 4;
        lesserSuccessLog.SetTextVariable("LESSER_REWARD", num);
        this.AddLog(lesserSuccessLog);
        GainRenownAction.Apply(Hero.MainHero, 5f);
        GiveGoldAction.ApplyForQuestBetweenCharacters((Hero) null, Hero.MainHero, num);
        this.RelationshipChangeWithQuestGiver = 1;
        foreach (Settlement settlement in this.QuestGiver.Clan.Settlements.Where<Settlement>((Func<Settlement, bool>) (x => x.IsFortification)))
        {
          settlement.Town.Security += 2f;
          settlement.Town.Loyalty += 2f;
        }
        this.CompleteQuestWithSuccess();
      }

      private void QuestSuccess(int boost)
      {
        this.AddLog(this.QuestSuccessLog);
        this.RelationshipChangeWithQuestGiver = 5;
        GiveGoldAction.ApplyForQuestBetweenCharacters((Hero) null, Hero.MainHero, this.RewardGold);
        foreach (Settlement settlement in this.QuestGiver.Clan.Settlements.Where<Settlement>((Func<Settlement, bool>) (x => x.IsFortification)))
        {
          settlement.Town.Security += (float) boost;
          settlement.Town.Loyalty += (float) boost;
        }
        this.CompleteQuestWithSuccess();
      }

      private void OnMapEventStarted(
        MapEvent mapEvent,
        PartyBase attackerParty,
        PartyBase defenderParty)
      {
        if (!QuestHelper.CheckMinorMajorCoercion((QuestBase) this, mapEvent, attackerParty))
          return;
        QuestHelper.ApplyGenericMinorMajorCoercionConsequences((QuestBase) this, mapEvent);
      }

      private void OnClanChangedKingdom(
        Clan clan,
        Kingdom oldKingdom,
        Kingdom newKingdom,
        ChangeKingdomAction.ChangeKingdomActionDetail detail,
        bool showNotification = true)
      {
        if (clan == Clan.PlayerClan && oldKingdom == this.QuestGiver.MapFaction)
        {
          this.AddLog(this.LeftFaction);
          this.CompleteQuestWithFail();
        }
        else if (clan.Settlements.Contains(this._targetSettlement))
        {
          if (newKingdom == this.QuestGiver.MapFaction)
          {
            this.QuestSuccess(1);
          }
          else
          {
            TextObject toAnotherFaction = this.DefectedToAnotherFaction;
            toAnotherFaction.SetTextVariable("FACTION_NAME", newKingdom.EncyclopediaLinkWithName);
            this.CompleteQuestWithCancel(toAnotherFaction);
          }
        }
        else
        {
          if (!this.QuestGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
            return;
          this.CompleteQuestWithCancel(this.WarDeclaredQuestCancelLog);
        }
      }

      private void OnWarDeclared(
        IFaction faction1,
        IFaction faction2,
        DeclareWarAction.DeclareWarDetail detail)
      {
        QuestHelper.CheckWarDeclarationAndFailOrCancelTheQuest((QuestBase) this, faction1, faction2, detail, this.PlayerDeclaredWarQuestLogText, this.WarDeclaredQuestCancelLog);
      }

      protected override void InitializeQuestOnGameLoad() => this.SetDialogs();

      protected override void OnTimedOut()
      {
        this.AddLog(this.QuestTimeOutFailLog);
        this.RelationshipChangeWithQuestGiver = -10;
        foreach (Settlement settlement in this.QuestGiver.Clan.Settlements.Where<Settlement>((Func<Settlement, bool>) (x => x.IsFortification)))
        {
          settlement.Town.Security += -10f;
          settlement.Town.Loyalty += -10f;
        }
      }
    }

    public class TheConquestOfSettlementIssueTypeDefiner : SaveableTypeDefiner
    {
      public TheConquestOfSettlementIssueTypeDefiner()
        : base(620000)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (TheConquestOfSettlementIssueBehavior.TheConquestOfSettlementIssue), 1);
        this.AddClassDefinition(typeof (TheConquestOfSettlementIssueBehavior.TheConquestOfSettlementIssueQuest), 2);
      }
    }
  }
}
